// Author	: damphat@gmail.com
// Created	: 01/12/2008

#pragma once
#include "vn/BasicTypes.h"
#include "vn/CommonChecks.h"

class Mem {
public:
	template<class T>
	static int Sign(T x) {
		return x < 0 ? -1 : 1;
	}

public:
	template<class T>
	static int Compare(const T *buf1, const T *buf2, Int64 len) {
		CHECK_ARG_BUFFER(buf1, len);
		CHECK_ARG_BUFFER(buf2, len);

		for(Int64 i = 0; i < len; i++) {
			if(*buf1 != *buf2)
				return Sign(*buf1 - *buf2);

			buf1++;
			buf2++;
		}

		return 0;
	}

	template<class T>
	static Int64 FindFirst(const T *buf, Int64 len, T ch) {
		CHECK_ARG_BUFFER(buf, len);

		const T *p		= buf;
		const T *end	= buf + len;

		while(p != end) {
			if(*p == ch)
				return p - buf;
			p++;
		}

		return -1;
	}

	template<class T>
	static Int64 FindFirst(const T *buf, Int64 buflen, const T *sub, Int64 sublen) {
		CHECK_ARG_BUFFER(buf, buflen);
		CHECK_ARG_BUFFER(sub, sublen);

		if(sublen > buflen)
			return -1;

		const T *p		= buf;
		const T *end	= buf + (buflen - sublen + 1);

		while(p != end) {
			if(0 == Compare(p, sub, sublen))
				return p - buf;
			p++;
		}

		return -1;
	}

	template<class T>
	static void Copy(T *buf1, const T *buf2, Int64 len) {
		memcpy(buf1, buf2, len * sizeof(T));
	}
};
